package com.ruoyi.basicsystem.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.RedisConstant;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.material.domain.ZnMaterialCurrentStock;
import com.ruoyi.material.mapper.ZnMaterialCurrentStockMapper;
import com.ruoyi.system.domain.SaveBusinessVO;
import com.ruoyi.system.domain.ZnCompanyConfig;
import com.ruoyi.system.domain.ZnUserBusiness;
import com.ruoyi.system.service.IZnCompanyConfigService;
import com.ruoyi.system.service.IZnUserBusinessService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basicsystem.mapper.ZnDepotMapper;
import com.ruoyi.basicsystem.domain.ZnDepot;
import com.ruoyi.basicsystem.service.IZnDepotService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 仓库Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-28
 */
@Service
public class ZnDepotServiceImpl implements IZnDepotService 
{
    @Autowired
    private ZnDepotMapper znDepotMapper;
    @Autowired
    private ZnMaterialCurrentStockMapper znMaterialCurrentStockMapper;
    @Autowired
    private IZnCompanyConfigService znCompanyConfigService;
    @Autowired
    private IZnUserBusinessService znUserBusinessService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询仓库
     * 
     * @param id 仓库主键
     * @return 仓库
     */
    @Override
    public ZnDepot selectZnDepotById(Long id)
    {
        return znDepotMapper.selectZnDepotById(id);
    }

    /**
     * 查询仓库列表
     * 
     * @param znDepot 仓库
     * @return 仓库
     */
    @Override
    public List<ZnDepot> selectZnDepotList(ZnDepot znDepot)
    {
        znDepot.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        znDepot.setDeleteFlag("0");
        return znDepotMapper.selectZnDepotList(znDepot);
    }

    /**
     * 新增仓库
     * 新增仓库的同时，也更新当前库存表，新增该仓库的当前期库存记录
     * @param znDepot 仓库
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertZnDepot(ZnDepot znDepot)
    {
        znDepot.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        znDepot.setIsDefault(0);
        int row = znDepotMapper.insertZnDepot(znDepot);
        //更新商品当前库存
        if(row>0){
            ZnMaterialCurrentStock znMaterialCurrentStock = new ZnMaterialCurrentStock();
            znMaterialCurrentStock.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
            znMaterialCurrentStock.setDepotId(znDepot.getId());
            znMaterialCurrentStockMapper.batchInsertZnMaterialCurrentStock(znMaterialCurrentStock);

            ZnCompanyConfig znCompanyConfig= redisCache.getCacheObject(RedisConstant.SYSTEM_CONFIG+"_"+SecurityUtils.getTenantId());
            if(znCompanyConfig!=null){
                boolean depotFlag ="1".equals(znCompanyConfig.getDepotFlag())?true:false; //获取系统配置，是否需要用户需要分配客户，暂时先写false
                if(depotFlag) {
                    StringBuffer depotIdsStr =  new StringBuffer();
                    SaveBusinessVO saveBusinessVO =new SaveBusinessVO();
                    saveBusinessVO.setUserId(SecurityUtils.getUserId());
                    saveBusinessVO.setType("UserDepot");
                    saveBusinessVO.setTenantId(SecurityUtils.getTenantId());
                    ZnUserBusiness znUserBusiness = znUserBusinessService.selectZnUserBusinessByUserIdAndType(saveBusinessVO);
                    List<Long> values=new ArrayList<>();
                    if(null!=znUserBusiness&&znUserBusiness.getValue()!=null){
                        znUserBusiness.setValue( znUserBusiness.getValue()+","+znDepot.getId());
                        znUserBusinessService.updateZnUserBusiness(znUserBusiness);
                        depotIdsStr.append(znUserBusiness.getValue()+","+znDepot.getId());
                    }else{
                        znUserBusiness = new ZnUserBusiness();
                        BeanUtils.copyProperties(saveBusinessVO,znUserBusiness);
                        znUserBusiness.setValue(znDepot.getId().toString());
                        znUserBusiness.setDeleteFlag("0");
                        znUserBusinessService.insertZnUserBusiness(znUserBusiness);
                        depotIdsStr.append(znDepot.getId());
                    }
                    String[] strs = depotIdsStr.toString().split(",");
                    redisCache.setCacheList (RedisConstant.SYSTEM_CONFIG_USER_DEPOT_LIST +"_"+SecurityUtils.getTenantId(), Arrays.asList(strs));
                }
            }
        }
        return row;
    }

    /**
     * 修改仓库
     * 
     * @param znDepot 仓库
     * @return 结果
     */
    @Override
    public int updateZnDepot(ZnDepot znDepot)
    {
        return znDepotMapper.updateZnDepot(znDepot);
    }

    /**
     * 批量删除仓库
     * 
     * @param ids 需要删除的仓库主键
     * @return 结果
     */
    @Override
    public int deleteZnDepotByIds(Long[] ids)
    {
        return znDepotMapper.deleteZnDepotByIds(ids);
    }

    /**
     * 删除仓库信息
     * 
     * @param id 仓库主键
     * @return 结果
     */
    @Override
    public int deleteZnDepotById(Long id)
    {
        return znDepotMapper.deleteZnDepotById(id);
    }

    @Override
    @Transactional
    public AjaxResult handleIsDefault(Long id) {
        ZnDepot znDepot=new ZnDepot();
        znDepot.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        znDepot.setIsDefault(0);
        znDepotMapper.updateZnDepotALL(znDepot);

        ZnDepot znDepot2=new ZnDepot();
        znDepot2.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        znDepot2.setIsDefault(1);
        znDepot2.setId(id);
       int count= znDepotMapper.updateZnDepot(znDepot2);
        return count>0?AjaxResult.success():AjaxResult.error();
    }

    @Override
    public JSONArray findDepotByCurrentUser() {
        JSONArray arr = new JSONArray();
        String type = "UserDepot";
        SysUser user=SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        ZnDepot znDepotQuery=new ZnDepot();
        List<ZnDepot> dataList = this.selectZnDepotList(znDepotQuery);
        //开始拼接json数据
        if (null != dataList) {
            ZnCompanyConfig znCompanyConfig=znCompanyConfigService.selectZnCompanyConfigBytenantId(user.getTenantId());
            boolean depotFlag ="1".equals(znCompanyConfig.getDepotFlag())?true:false; //获取系统配置，是否需要用户需要分配仓库，暂时先写false
            if(depotFlag) {
                SaveBusinessVO saveBusinessVO =new SaveBusinessVO();
                saveBusinessVO.setUserId(userId);
                saveBusinessVO.setType(type);
                saveBusinessVO.setTenantId(user.getTenantId());
                ZnUserBusiness znUserBusiness = znUserBusinessService.selectZnUserBusinessByUserIdAndType(saveBusinessVO);
                List<Long> values=new ArrayList<>();
                if(null!=znUserBusiness&&znUserBusiness.getValue()!=null){
                    String[] strs=   znUserBusiness.getValue().split(",");
                    for (ZnDepot depot : dataList) {
                        for(String depotId:strs){
                            if(depot.getId() == Long.parseLong(depotId)){
                                JSONObject item = new JSONObject();
                                item.put("id", depot.getId());
                                item.put("depotName", depot.getName());
                                item.put("isDefault", depot.getIsDefault());
                                arr.add(item);
                            }
                        }
                    }
                }
            } else {
                for (ZnDepot depot : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", depot.getId());
                    item.put("depotName", depot.getName());
                    item.put("isDefault", depot.getIsDefault());
                    arr.add(item);
                }
            }
        }
        return arr;
    }

    @Override
    public List<ZnDepot> findDepotByCurrentUser(ZnDepot znDepot) {
        List<ZnDepot> znDepots = new ArrayList<>();
        String type = "UserDepot";
        SysUser user=SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        ZnDepot znDepotQuery=new ZnDepot();
        List<ZnDepot> dataList = this.selectZnDepotList(znDepotQuery);
        //开始拼接json数据
        if (null != dataList) {
            ZnCompanyConfig znCompanyConfig=znCompanyConfigService.selectZnCompanyConfigBytenantId(user.getTenantId());
            boolean depotFlag ="1".equals(znCompanyConfig.getDepotFlag())?true:false; //获取系统配置，是否需要用户需要分配仓库，暂时先写false
            if(depotFlag) {
                SaveBusinessVO saveBusinessVO =new SaveBusinessVO();
                saveBusinessVO.setUserId(userId);
                saveBusinessVO.setType(type);
                saveBusinessVO.setTenantId(user.getTenantId());
                ZnUserBusiness znUserBusiness = znUserBusinessService.selectZnUserBusinessByUserIdAndType(saveBusinessVO);
                List<Long> values=new ArrayList<>();
                if(null!=znUserBusiness&&znUserBusiness.getValue()!=null){
                    String[] strs=   znUserBusiness.getValue().split(",");
                    for (ZnDepot depot : dataList) {
                        for(String depotId:strs){
                            if(depot.getId() == Long.parseLong(depotId)){
                                znDepots.add(depot);
                            }
                        }
                    }
                }
            } else {
                for (ZnDepot depot : dataList) {
                    znDepots.add(depot);
                }
            }
        }
        return znDepots;
    }

    @Override
    public List<ZnDepot> selectZnDepotSelectList(ZnDepot znDepot) {
        List<ZnDepot> list = znDepotMapper.selectZnDepotList(znDepot);
        List<ZnDepot> result = new ArrayList<>();
        if(list.size()>0){
            ZnCompanyConfig znCompanyConfig= redisCache.getCacheObject(RedisConstant.SYSTEM_CONFIG+"_"+SecurityUtils.getTenantId());
            if(znCompanyConfig!=null){
                boolean depotFlag ="1".equals(znCompanyConfig.getDepotFlag())?true:false; //获取系统配置，是否需要用户需要分配仓库，暂时先写false
                if(depotFlag) {
                    List<String> depotIds = redisCache.getCacheList(RedisConstant.SYSTEM_CONFIG_USER_DEPOT_LIST +"_"+SecurityUtils.getTenantId());
                    List<Long> values=new ArrayList<>();
                    if(null!=depotIds&&depotIds.size()>0){
                        for (ZnDepot depot : list) {
                            for(String depotId:depotIds){
                                if(depot.getId() == Long.parseLong(depotId)){
                                    result.add(depot);
                                }
                            }
                        }
                    }
                }else{
                    result.addAll(list);
                }
            }else{
                result.addAll(list);
            }
        }
        return result;
    }
}
